import React, { useState, useMemo, useEffect } from 'react'
import 'antd/dist/antd.less'
import './global.less'
import { ConfigProvider } from 'antd'
import zhCN from 'antd/lib/locale/zh_CN'
import enUS from 'antd/lib/locale/en_US'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { getSchema } from './service/index'
import ReactDOM from 'react-dom'
import { IntlProvider } from 'react-intl'
import { getLanguagePackage } from '../../../packages/event-system/src/locale'
import { BrowserRouter, Route } from 'react-router-dom'
import { setValidateLanguage } from '@formily/validator'
import { setNpmCDNRegistry } from '@designable/react-settings-form'
import { SchemaApp } from '../src/customComponents/SchemaApp'
setNpmCDNRegistry('//unpkg.com')
const locale = localStorage.getItem('umi_locale') || 'zh-CN'
const antdLocales: Record<string, any> = {
  'zh-CN': zhCN,
  'en-US': enUS,
}

// 设置 moment 语言
moment.locale(locale === 'zh-CN' ? 'zh-cn' : 'en')

type LanguageMessage = {
  language: string
  locale: Record<string, any>
}

type PageSchema = {
  page?: any
  schema?: any
}

// 国际化容器组件，负责处理所有国际化相关逻辑
const IntlApp: React.FC<{ pageName: string }> = ({ pageName }) => {
  const [langPkg, setLangPkg] = useState<LanguageMessage[]>([])
  const [pageSchema, setPageSchema] = useState<PageSchema>({
    page: null,
    schema: null,
  })

  const currentMessages = useMemo(() => {
    return langPkg.find((item) => item.language === locale)?.locale
  }, [langPkg, locale])

  useEffect(() => {
    setValidateLanguage(locale)
  }, [])

  const getLangPkg = async () => {
    if (langPkg.length > 0) return
    try {
      const res = await getLanguagePackage('intl-web', 'main')
      setLangPkg(res)
    } catch (error) {
      // 静默处理错误
    }
  }

  useEffect(() => {
    getLangPkg()
  }, [])

  const fetchSchema = async () => {
    try {
      if (!pageName.includes('lowcodePreview')) return
      const res = await getSchema(pageName)
      setPageSchema(res)
    } catch (error) {
      // 静默处理错误
    }
  }

  // 获取页面 schema 数据 - 只有当 pageName 发生变化时才执行
  useEffect(() => {
    fetchSchema()
  }, [pageName])
  const schemaAppElement = useMemo<React.ReactElement>(() => {
    if (!pageSchema.schema) {
      return <div>Loading...</div>
    }
    return (
      <SchemaApp
        pageSchema={{
          schema: pageSchema.schema,
          formProps: pageSchema.page,
        }}
      />
    )
  }, [pageSchema])

  if (!currentMessages) {
    return <div>Loading...</div>
  }

  return (
    <IntlProvider messages={currentMessages} locale={locale}>
      <ConfigProvider locale={antdLocales[locale]}>
        {schemaAppElement}
      </ConfigProvider>
    </IntlProvider>
  )
}

const cleanUrl = (url: string): string => {
  if (!url) return url
  // 删除查询参数和hash，只保留路径部分
  return url.split('?')[0].split('#')[1]
}
const App = (
  <BrowserRouter>
    <Route
      path="/"
      render={(routeProps: any) => {
        const pageName = routeProps.location.hash
        return <IntlApp pageName={cleanUrl(pageName)} />
      }}
    />
  </BrowserRouter>
)

const root = document.getElementById('root')
if (!(window as any).__POWERED_BY_QIANKUN__) {
  ReactDOM.render(App, root)
}

export async function bootstrap() {}

export async function mount(props: any) {
  const container = props.container
    ? props.container.querySelector('#root')
    : root
  // Ensure a clean mount each time
  if (container) {
    ReactDOM.unmountComponentAtNode(container)
  }
  ReactDOM.render(App, container)
  props?.setLoading?.(false)
}

export async function unmount(props: any) {
  ReactDOM.unmountComponentAtNode(
    props.container ? props.container.querySelector('#root') : root
  )
}

export async function update() {}
